package com.rice.apiproject.controller;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 提供API接口的控制类
 * @author 米饭好好吃
 */
@RestController
@RequestMapping("/name")
@Slf4j
public class ApiController {

    private String genSign(String accessKey, String secretKey, String randomStr, String timeStamp) {
        Digester digester = new Digester(DigestAlgorithm.SHA256);
        String originInfo = accessKey + randomStr + timeStamp + secretKey;
        return digester.digestHex(originInfo);
    }

    @GetMapping("/")
    public String getNameByGet(String name) {
        log.info("请求路径为 / , 请求方式为GET, 携带参数为" + name);
        return "您的名称为: " + name;
    }

    @PostMapping("/")
    public String getNameByPost(@RequestBody String name) {
        log.info("请求路径为 / , 请求方式为POST, 携带参数为" + name);
        return "您的名称为: " + name;
    }

    @PostMapping("/user")
    public String getNameByPost(@RequestBody Map<String, String> bodyMap) {
        log.info("请求路径为 / , 请求方式为POST, 携带参数为" + bodyMap.toString());
        // 1. 获取传递信息
        String accessKey = bodyMap.get("accessKey");
        String sign = bodyMap.get("sign");
        String randomNum = bodyMap.get("randomNum");
        String timeStamp = bodyMap.get("timeStamp");
        String name = bodyMap.get("name");
        // 2. 进行校验
        // 2.1 校验时间戳
        // 2.2 校验随机数
        // 2.3 校验sign
        String secretKey = "QWEzxc123";
        String validSign = genSign(accessKey, secretKey, randomNum, timeStamp);
        if (!validSign.equals(sign)) {
            throw new RuntimeException("权限不足!");
        }
        return "您的名称为: " + name;
    }
}
